package org.zpmis.api.http;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.zpmis.common.result.PlatformResult;
import org.zpmis.common.result.ResultCode;
import org.zpmis.domain.wechat.config.WxMpProperties;
import org.zpmis.domain.wechat.qo.SendWxTemplateQo;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WeChatController {
    /**
     * 微信公众号API的Service
     */
    private final WxMpService wxMpService;

    /**
     * 构造注入
     */
    WeChatController(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    @Resource
    private WxMpProperties wxMpProperties;


    @GetMapping("authorize")
    public String authorize(@RequestParam(value = "returnUrl",required=true) String returnUrl) throws Exception {
        //自己编写获得openid的路径 在下面定义方法getUserInfo
        String url = wxMpProperties.getRedirectUrl()+"/message/wechat/getUserInfo";
        /**
         * 第一个参数是获得授权码code后回调的地址
         * 第二个是策略：获得简单的授权，还是希望获得用户的信息
         * 第三个参数是我们希望携带的参数:查看API文档需要返回returnUrl 所以我们就携带它
         */
        String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl,"UTF-8"));
        return "redirect:"+redirectUrl;

    }


    /**
     * code:是授权码
     * returnUrl：是刚才我们自己传递的参数  会传递到微信然后传回来
     */
    @GetMapping("getUserInfo")
    @ResponseBody
    public PlatformResult getUserInfo(@RequestParam("code")String code,
                              @RequestParam("state") String returnUrl) throws UnsupportedEncodingException {
        WxOAuth2AccessToken wxOAuth2AccessToken;
        try {
            //根据sdk文档 通过code获得令牌与openid
            wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("微信获得access_token异常:{}",e.getError().getErrorMsg());
            return PlatformResult.failure();
        }

        try {
            //获得用户信息
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
            log.info("获得用户信息:{}",wxMpUser.toString());
            //返回用户信息
            return PlatformResult.success(wxMpUser);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return PlatformResult.failure();
        }
    }

    /**
     * 意向回访成功后 给注册意向用户发送模板消息
     * @param sendWxTemplateQo
     * @return
     */
    @PostMapping(value = "/sendWxTemplate")
    @ResponseBody
    public PlatformResult sendWxTemplate(@Valid @RequestBody SendWxTemplateQo sendWxTemplateQo){
        //配置跳转小程序的appid和pagepath
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(wxMpProperties.getMiniAppId());
        miniProgram.setPagePath("pages/register/register?name="+sendWxTemplateQo.getCompanyName()+"&contactPerson="+sendWxTemplateQo.getContactPerson()+"&contactMobile="+sendWxTemplateQo.getContactMobile()+"&companyCode="+sendWxTemplateQo.getCompanyCode());
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(sendWxTemplateQo.getOpenId())
                // 模板id
                .templateId("YNQmsXHsLrqrIebGPYFhEPc49p0hYXynDAlHHNgnMRo")
                // 模板跳转链接
                //.url("http://www.cpzs.net.cn/")
                .miniProgram(miniProgram)
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", "您的意向已成功回访,请及时处理", "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", sendWxTemplateQo.getCompanyName(), "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword2", sendWxTemplateQo.getContactPerson(), "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword3", sendWxTemplateQo.getContactMobile(), "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword4", sendWxTemplateQo.getTime(), "#A9A9A9"))
                .addData(new WxMpTemplateData("remark", "点击小程序注册企业，完善您的信息。", "#000000"));
        try {
            String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.info("公众号模板消息发送成功："+msg);
            return PlatformResult.success();
        } catch (Exception e) {
            log.info("公众号模板消息发送失败："+e.getMessage());
            e.printStackTrace();
            return PlatformResult.failure(ResultCode.WX_TEMPLATE_SEND_ERROR,e.getMessage());
        }
    }
}
